<template>
  <div class="settings-container">
    <div class="settings-header">
      <h1>系统设置</h1>
      <el-button type="primary" @click="handleSaveAll" :loading="saving">
        <el-icon><Check /></el-icon>
        保存所有设置
      </el-button>
    </div>

    <div class="settings-content" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="formData" 
        label-width="120px"
        v-if="configList && configList.length > 0"
      >
        <el-card 
          v-for="(config, index) in configList" 
          :key="config.id || index"
          class="config-card"
          shadow="hover"
        >
          <template #header>
            <div class="card-header">
              <span class="config-title">{{ config.title }}</span>
              <el-tag size="small" :type="config.input_type === 'textarea' ? 'warning' : 'info'">
                {{ config.input_type === 'textarea' ? '富文本' : '文本输入' }}
              </el-tag>
            </div>
          </template>

          <el-form-item :label="config.title" :prop="`config_${config.id || index}`">
            <!-- 提示信息 -->
            <div v-if="config.tip" class="config-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>{{ config.tip }}</span>
            </div>

            <!-- 普通输入框 -->
            <el-input
              v-if="config.input_type === 'input'"
              v-model="formData[`config_${config.id || index}`]"
              :placeholder="`请输入${config.title}`"
              clearable
              show-word-limit
              maxlength="500"
            />

            <!-- 富文本编辑器 -->
            <div v-else-if="config.input_type === 'textarea'" class="editor-container">
              <QuillEditor
                v-model:content="formData[`config_${config.id || index}`]"
                :options="editorOptions"
                content-type="html"
                style="height: 300px;"
                :placeholder="`请输入${config.title}内容...`"
              />
            </div>

            <!-- 预览区域 -->
            <!-- <div class="preview-section" v-if="formData[`config_${config.id || index}`]">
              <el-divider content-position="left">
                <el-icon><View /></el-icon>
                预览
              </el-divider>
              <div 
                v-if="config.input_type === 'textarea'"
                class="rich-text-preview"
                v-html="formData[`config_${config.id || index}`]"
              ></div>
              <div v-else class="text-preview">
                {{ formData[`config_${config.id || index}`] }}
              </div>
            </div> -->
          </el-form-item>
        </el-card>
      </el-form>

      <!-- 空状态 -->
      <el-empty v-else description="暂无配置项" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfig, updateConfig } from '@/api/config'

// 富文本编辑器相关导入
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const loading = ref(true)
const saving = ref(false)
const configList = ref([])
const formData = reactive({})
const formRef = ref()

// Quill 编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link']
    ]
  }
}

// 获取配置数据
const fetchConfig = async () => {
  try {
    loading.value = true
    const res = await getConfig()
    
    if (res.code === 1) {
      configList.value = res.data || []
      
      // 初始化表单数据
      configList.value.forEach((config, index) => {
        const key = `config_${config.id || index}`
        formData[key] = config.content || ''
      })
    } else {
      ElMessage.error(res.msg || '获取配置失败')
    }
  } catch (error) {
    console.error('获取配置错误:', error)
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

// 保存所有设置
const handleSaveAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要保存所有设置吗？',
      '确认保存',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    saving.value = true
    
    // 构建更新数据
    const updateData = configList.value.map((config, index) => {
      const key = `config_${config.id || index}`
      return {
        id: config.id,
        content: formData[key] || ''
      }
    })

    const res = await updateConfig(updateData)
    
    if (res.code === 1) {
      ElMessage.success('保存成功')
      // 重新获取最新数据
      await fetchConfig()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存设置错误:', error)
      ElMessage.error('保存失败')
    }
  } finally {
    saving.value = false
  }
}

// Quill 编辑器会自动处理清理，无需手动销毁

onMounted(() => {
  fetchConfig()
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.settings-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.settings-content {
  max-width: 1200px;
}

.config-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-title {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.config-tip {
  display: inline-flex;
  width: 100%;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 4px;
  margin-bottom: 16px;
  color: #0277bd;
  font-size: 14px;
}

.config-tip .el-icon {
  color: #03a9f4;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.preview-section {
  margin-top: 20px;
}

.rich-text-preview {
  padding: 16px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  min-height: 100px;
  line-height: 1.6;
}

.rich-text-preview :deep(img) {
  max-width: 100%;
  height: auto;
}

.text-preview {
  padding: 16px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
  word-break: break-all;
}

/* 深色主题适配 */
:deep(.w-e-text-container) {
  background-color: #fff !important;
}

:deep(.w-e-text-placeholder) {
  color: #c0c4cc !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-container {
    padding: 10px;
  }
  
  .settings-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .settings-header h1 {
    font-size: 20px;
  }
  
  .config-card {
    margin-bottom: 16px;
  }
  
  :deep(.el-form-item__label) {
    width: 100px !important;
  }
}
</style>